package com.chuhe.starry.controller;

import com.chuhe.common.constans.MyConstants;
import com.chuhe.common.domain.dto.MessageSendDto;
import com.chuhe.common.domain.dto.TokenUserInfoDto;
import com.chuhe.common.domain.entity.ChatMessage;
import com.chuhe.common.domain.enums.MessageTypeEnum;
import com.chuhe.common.domain.vo.resp.ApiResult;
import com.chuhe.common.exception.BusinessException;
import com.chuhe.common.exception.CommonErrorEnum;
import com.chuhe.common.utils.AppConfig;
import com.chuhe.common.utils.RedisComponet;
import com.chuhe.common.utils.StringTools;
import com.chuhe.starry.service.ChatMessageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Max;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @Author: 楚河
 * @Date: 2025年05月24日12:56
 */
@RestController
@RequestMapping("/chat")
@Slf4j
@Api(value = "发消息接口", tags = "发消息相关API", description = "发消息相关API")
public class ChatController {
    @Autowired
    private ChatMessageService chatMessageService;
    @Autowired
    private AppConfig appConfig;
    @Autowired
    private RedisComponet redisComponet;

    @RequestMapping("/sendMessage")
    @ApiOperation("发送消息")
    public ApiResult<?> sendMessage(HttpServletRequest request,
                                    @NotEmpty String contactId,
                                    @NotEmpty @Max(500) String messageContent,
                                    @NotNull Integer messageType,
                                    Long fileSize,
                                    String fileName,
                                    Integer fileType){
        MessageTypeEnum messageTypeEnum = MessageTypeEnum.getByType(messageType);
        if(messageTypeEnum == null || !ArrayUtils.contains(new Integer[]{MessageTypeEnum.CHAT.getType(),MessageTypeEnum.MEDIA_CHAT.getType()},messageType)){
            throw new BusinessException("该消息类型不支持");
        }
        TokenUserInfoDto tokenUserInfoDto = redisComponet.getTokenUserInfoByToken(request);
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setContactId(contactId);
        chatMessage.setMessageContent(messageContent);
        chatMessage.setFileSize(fileSize);
        chatMessage.setFileName(fileName);
        chatMessage.setFileType(fileType);
        chatMessage.setMessageType(messageType);
        MessageSendDto messageSendDto = chatMessageService.saveMessage(chatMessage,tokenUserInfoDto);
        return ApiResult.success(messageSendDto);
    }

    @RequestMapping("uploadFile")
    public ApiResult<?> uploadFile(HttpServletRequest request,
                                 @NotNull Long messageId,
                                 @NotNull MultipartFile file,
                                 @NotNull MultipartFile cover) {
        TokenUserInfoDto tokenUserInfoDto = redisComponet.getTokenUserInfoByToken(request);
        chatMessageService.saveMessageFile(tokenUserInfoDto.getUserId(), messageId, file, cover);
        return ApiResult.success(null);
    }

    @RequestMapping("downloadFile")
    public void downloadFile(HttpServletRequest request, HttpServletResponse response,
                             @NotEmpty String fileId,
                             @NotNull Boolean showCover) throws Exception {
        TokenUserInfoDto userInfoDto = redisComponet.getTokenUserInfoByToken(request);
        OutputStream out = null;
        FileInputStream in = null;
        try {
            File file = null;
            if (!StringTools.isNumber(fileId)) {
                String avatarFolderName = MyConstants.FILE_FOLDER_FILE + MyConstants.FILE_FOLDER_AVATAR_NAME;
                String avatarPath = appConfig.getProjectFolder() + avatarFolderName + fileId + MyConstants.IMAGE_SUFFIX;
                if (showCover) {
                    avatarPath = avatarPath + MyConstants.COVER_IMAGE_SUFFIX;
                }
                file = new File(avatarPath);
                if (!file.exists()) {
                    throw new BusinessException(CommonErrorEnum.CODE_602);
                }
            } else {
                file = chatMessageService.downloadFile(userInfoDto, Long.parseLong(fileId), showCover);
            }
            response.setContentType("application/x-msdownload; charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;");
            response.setContentLengthLong(file.length());
            in = new FileInputStream(file);
            byte[] byteData = new byte[1024];
            out = response.getOutputStream();
            int len = 0;
            while ((len = in.read(byteData)) != -1) {
                out.write(byteData, 0, len);
            }
            out.flush();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    log.error("IO异常", e);
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    log.error("IO异常", e);
                }
            }
        }
    }

}
